package com.tcm.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

public class ConsumerFastStart {

    public static final String brokeList = "localhost:9092";
    public static final String topic = "topic-demo";
    public static final String groupId = "group.demo";

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("bootstrap.servers", brokeList);
        // 设置消费组的名称
        properties.put("group.id", groupId);
        properties.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, ConsumerInterceptorTTL.class.getName());
        //创建一个消费者客户端实例
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        //订阅主题
        consumer.subscribe(Collections.singletonList(topic));
//        List<PartitionInfo> partitionInfos = consumer.partitionsFor(topic, Duration.ofMillis(1000));
//        List<TopicPartition> list = new ArrayList();
//        for(PartitionInfo partitionInfo : partitionInfos){
//            TopicPartition partition = new TopicPartition(partitionInfo.topic(), partitionInfo.partition());
//            list.add(partition);
//        }
//        consumer.assign(list);
        // 取消订阅
//        consumer.unsubscribe();
        //循环消费消息
        while(true){
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
            for(ConsumerRecord<String, String> record:records){
                System.out.println(record.value());
            }
        }

        //根据分区消费消息
//        while(true){
//            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
//            for(TopicPartition partition : records.partitions()) {
//                for (ConsumerRecord<String, String> record : records.records(partition)) {
//                    System.out.println(record.value());
//                }
//            }
//        }
    }

}
